import axios from 'axios';
// 引入路由信息
import {ElMessage} from "element-plus";
// 设置超时时间
axios.defaults.timeout = 50000;
// 设置默认请求地址
axios.defaults.baseURL = `${import.meta.env.VITE_MODE_API_PROTOCOL}${import.meta.env.VITE_MODE_API_IP}${import.meta.env.VITE_MODE_API_POOT}`
// 创建一个axios请求
const $axios = axios.create();
// 记录当前弹窗信息对象
let tipsObj = {}

/**
 * @author: 王琛
 * @description: 初始化axios
 * @Date: 2021-10-19 16:48:02
 * @param {*}
 * @return {*}
 */
function initAxios({url, method, params = {}, headers = {}}) {
    const modeList = ["put", "post", "patch"];
    // modeList.includes(method);
    const config = {
        url,
        method,
        [modeList.includes(method) ? 'data' : 'params']: params,
        headers,
    }
    return $axios.request(config);
}

/**
 * @author: 王琛
 * @description: 请求前拦截
 * @Date: 2021-10-19 16:46:23
 * @param {*}
 * @return {*}
 */
$axios.interceptors.request.use(
    config => {
        config.headers["Content-Type"] = "application/json";
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
/**
 * @author: 王琛
 * @description: 响应后拦截
 * @Date: 2021-10-19 16:46:50
 * @param {*}
 * @return {*}
 */
$axios.interceptors.response.use(response => {
    // 判断当前是否是UE4的街口地址
    if (response.config.url.indexOf(import.meta.env.VITE_MOOE_UE4_IP) == -1 && response.data.code != 0) {
        // 说有code码提示信息
        const msgErr = {
            400: "请求参数错误",
            401: "未授权，请登录",
            403: "拒绝访问",
            404: `请求地址出错`,
            408: "请求超时",
            500: response.data.msg,
            501: "服务未实现",
            502: "网关错误",
            503: "服务不可用",
            504: "网关超时",
            505: "HTTP版本不受支持"
        }
    }
    return response.data;
}, err => {
    return err.response;
})

/**
 * @author: 王琛
 * @description: get请求
 * @Date: 2021-10-19 17:17:45
 * @param {*}
 * @return {*}
 */
function get(url, params = {}, headers = {}) {
    return initAxios({url, params, headers, method: 'get'});
}

/**
 * @author: 王琛
 * @description: post请求
 * @Date: 2021-10-19 17:17:45
 * @param {*}
 * @return {*}
 */
function post(url, params = {}, headers = {}) {
    return initAxios({url, params, headers, method: 'post'});
}

/**
 * @author: 王琛
 * @description: delete请求
 * @Date: 2021-10-19 17:17:45
 * @param {*}
 * @return {*}
 */
function del(url, params = {}, headers = {}) {
    return initAxios({url, params, headers, method: 'delete'});
}

/**
 * @author: 王琛
 * @description: put请求
 * @Date: 2021-10-19 17:17:45
 * @param {*}
 * @return {*}
 */
function put(url, params = {}, headers = {}) {
    return initAxios({url, params, headers, method: 'put'});
}

export default {put, get, post, del};